package org.jsbd.boss.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.jsbd.boss.domian.OnlineLoginData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoginUtil {

	private static List<OnlineLoginData> onlineLoginDataList;

	private static final Logger logger = LoggerFactory.getLogger(LoginUtil.class);

	public static void loadData(String onlineLoginDataFilenaname) {
		if (onlineLoginDataList == null) {
			onlineLoginDataList = new ArrayList<OnlineLoginData>();
		} else {
			onlineLoginDataList.clear();
		}
		try {
			List<String> lines = FileUtils.readLines(new File(onlineLoginDataFilenaname));
			for (String line : lines) {
				if (StringUtils.isEmpty(line)) {
					continue;
				}
				OnlineLoginData onlineLoginData = new OnlineLoginData();
				String data[] = line.split(",");
				if (data.length != 7) {
					continue;
				}
				onlineLoginData.setCid(data[0].trim());
				onlineLoginData.setChid(data[1].trim());
				onlineLoginData.setCpid(data[2].trim());
				onlineLoginData.setPackageName(data[3].trim());
				onlineLoginData.setAppName(data[4].trim());
				onlineLoginData.setVersionName(data[5].trim());
				onlineLoginData.setVersionCode(data[6].trim());
				onlineLoginDataList.add(onlineLoginData);
			}
			logger.info("应用数据初始化成功，共加载" + onlineLoginDataList.size() + "个应用");
		} catch (IOException e) {
			logger.error("应用数据初始化失败", e);
		}
	}

	public static OnlineLoginData getOnlineLoginData() {
		Random r = new Random();
		return onlineLoginDataList.get(r.nextInt(onlineLoginDataList.size()));
	}

	public static List<OnlineLoginData> getOnlineLoginDataList() {
		return onlineLoginDataList;
	}

}
